<template>
  <div class="avatar-upload">
    <el-upload
      class="avatar-uploader"
      action="/api/file/upload/avatar"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="uploadHeaders"
      accept="image/*"
    >
      <div class="avatar-container">
        <img 
          v-if="avatarUrl" 
          :src="getFullAvatarUrl(avatarUrl)" 
          class="avatar"
          alt="用户头像"
        />
        <div v-else class="avatar-placeholder">
          <el-icon class="avatar-icon"><Plus /></el-icon>
        </div>
        <div class="avatar-overlay">
          <el-icon class="upload-icon"><Camera /></el-icon>
          <span class="upload-text">更换头像</span>
        </div>
      </div>
    </el-upload>
    
    <!-- 上传提示 -->
    <div class="upload-tip">
      <el-text size="small" type="info">
        支持 JPG、PNG、GIF 等格式，文件大小不超过 10MB
      </el-text>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()

// 头像URL
const avatarUrl = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 上传请求头
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

// 获取完整的头像URL
const getFullAvatarUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  // 使用相对路径，通过代理转发到后端
  return `/api${url}`
}

// 上传前验证
const beforeUpload = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }

  // 检查文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传头像图片大小不能超过 10MB！')
    return false
  }

  ElMessage.info('正在上传头像...')
  return true
}

// 上传成功
const handleSuccess = (response) => {
  if (response.code === 200) {
    avatarUrl.value = response.data.avatar
    ElMessage.success('头像上传成功！')
    emit('success', response.data)
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 上传失败
const handleError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}
</script>

<style lang="scss" scoped>
.avatar-upload {
  text-align: center;

  .avatar-uploader {
    :deep(.el-upload) {
      border: 2px dashed #dcdfe6;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s ease;
      width: 120px;
      height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409eff;
        
        .avatar-overlay {
          opacity: 1;
        }
      }
    }
  }

  .avatar-container {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
  }

  .avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
  }

  .avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 50%;

    .avatar-icon {
      font-size: 32px;
      color: #c0c4cc;
    }
  }

  .avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    border-radius: 50%;

    .upload-icon {
      font-size: 24px;
      margin-bottom: 4px;
    }

    .upload-text {
      font-size: 12px;
    }
  }

  .upload-tip {
    margin-top: 12px;
  }
}
</style> 